<template>
  <div v-loading="loading" class="app-main-content-box business-store-edit">
    <!-- <app-main-title :title="type === 'edit' ? '修改店铺配置' : '新增店铺'" /> -->
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="130px"
      class="demo-ruleForm"
    >
      <!-- <el-form-item v-if="type === 'edit'" label="店铺状态：">
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-tag>{{ form.disabled ? '关停中' : '启用中' }}</el-tag>
            <el-tag type="danger" style="margin-left: 10px">{{
              STATUS_TEXT[form.status]
            }}</el-tag>
          </div>
          <div>
            <el-button type="danger" @click="onClickStopStore"
              >{{ form.disabled ? '启用' : '关停' }}店铺</el-button
            >
            <el-button v-if="!form.disabled" @click="onClickCloseStore"
              >{{ form.status === 0 ? '营业' : '打烊' }}
            </el-button>
          </div>
        </div>
      </el-form-item> -->

      <!-- <el-form-item label="店铺全称：" prop="fullName">
        <el-input
          v-model="form.fullName"
          placeholder="请输入"
          :disabled="form_disabled"
        />
      </el-form-item> -->
      <el-form-item label="店铺简称：" prop="shopName">
        <el-input
          v-model="form.shopName"
          placeholder="请输入"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <!--      支持商圈商户为主店、直营、独立门店配置门店分类，-->
      <el-form-item
        v-if="isBusinessDistrictMainStore"
        label="门店分类："
        prop="pubDomainClassifyId"
      >
        <el-select
          v-model="form.pubDomainClassifyId"
          placeholder="请选择门店分类"
        >
          <el-option
            v-for="item in businessClassificationList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!--      支持所有商户为主店、直营、独立门店配置门店类型-->
      <el-form-item
        v-if="isMainStore"
        label="门店类型："
        prop="pubDomainIndustryId"
      >
        <el-select
          v-model="form.pubDomainIndustryId"
          placeholder="请选择门店类型"
        >
          <el-option
            v-for="item in pubIndustryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!--      支持商户上传主店的图片，非主店、非商圈主店无图片字段，-->
      <el-form-item
        v-if="form.pubTag === 1 && form.shopType === 3"
        label="门店图片："
        prop="images"
      >
        <el-upload
          class="app-uploader-img-plus fl"
          :action="actionUrl"
          :show-file-list="false"
          :headers="uploadHeaders"
          :on-success="handleBusinessBgUploadSuccess"
          :before-upload="beforeBusinessBgUpload"
        >
          <img
            v-if="form.images"
            :src="fileBaseUrl + form.images"
            class="avatar"
          >
          <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
        </el-upload>
        <ul class="fl upload_tips">
          <li>图片要求：</li>
          <li>1.上传的图片限制文件大小不超过500KB，仅支持JPG/PNG格式</li>
          <li>2.像素大小控制在300像素*300像素以下</li>
<!--          <li>-->
<!--            <el-button-->
<!--              size="small"-->
<!--              round-->
<!--              @click="openCardImgMap"-->
<!--            >从系统图库中选择</el-button>-->
<!--          </li>-->
        </ul>
      </el-form-item>

      <el-form-item label="店铺地址：" prop="address">
        <el-form-item prop="provinceCode">
          <el-cascader
            v-model="selectedOptions"
            class="input-width-250"
            size="small"
            :options="options"
            :props="props"
            @change="handleChooseAddressChange"
          />
        </el-form-item>
        <el-input
          v-model="form.address"
          type="textarea"
          :autosize="{ minRows: 2 }"
          placeholder="请输入详细地址"
        />
      </el-form-item>

      <el-form-item label="店铺位置：" prop="latitude">
        <TencentMap
          :tencent-map-src="tencentMapSrc"
          @getPackingLocation="getPackingLocation"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="form.landmark"
          maxlength="20"
          show-word-limit
          placeholder="可输入地标，方便用户导航，如某某地铁出口，右转100m"
        />
      </el-form-item>

      <!-- <el-form-item prop="openTimeType" label="类型">
        <el-radio-group v-model="form.openTimeType" class="open_type">
          <el-radio :label="1"
            >营业时间
            <el-tooltip
              class="item"
              effect="dark"
              content="营业时间为商户24h内设置的店铺营业时间，不设置的时间为店铺非营业时间"
              placement="top"
            >
              <span class="el-icon-question" />
            </el-tooltip>
          </el-radio>
          <el-radio :label="2">
            非营时间
            <el-tooltip
              class="item"
              effect="dark"
              content="非营业时间为商户24h内设置的店铺非营业时间，不设置的时间为店铺营业时间"
              placement="top"
            >
              <span class="el-icon-question" />
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item label="营业时间：" prop="customParamsOpenTime">
        <el-time-picker
          v-model="form.customParamsOpenTime"
          is-range
          value-format="HH:mm"
          format="HH:mm"
          range-separator="~"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
        />
        <el-switch
          v-model="customParamsOpenTimeSwitch"
          style="margin-left: 20px"
          active-text="不营业"
          inactive-text=""
        />
      </el-form-item>

      <el-form-item label="店铺LOGO：" prop="logo">
        <el-upload
          class="app-uploader-img-plus fl"
          :action="actionUrl"
          :show-file-list="false"
          :headers="uploadHeaders"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.logo" :src="fileBaseUrl + form.logo" class="avatar">
          <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
        </el-upload>
        <ul class="fl upload_tips">
          <li>图片要求：</li>
          <li>1.上传的图片限制文件大小不超过500KB，仅支持JPG/PNG格式</li>
          <li>2.像素大小控制在300像素*300像素以下</li>
          <li>
            <el-button
              size="small"
              round
              @click="openCardImgMap"
            >从系统图库中选择</el-button>
          </li>
        </ul>
      </el-form-item>

      <el-form-item label="客服电话：" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="店铺描述：">
        <el-input
          v-model="form.desc"
          placeholder="请输入"
          type="textarea"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="店铺分享文案设置："
        label-width="160"
        prop="copywrite"
      >
        <el-input v-model="form.copywrite" placeholder="请输入" />
        <div class="default_msg">默认：新注册会员获取更多优惠</div>
      </el-form-item>

      <el-form-item v-if="form.industry <= 100" label="就餐方式：">
        <ul class="fl">
          <li>
            <el-switch
              v-model="form.diningConfigJson.isEatShop"
              active-text="注：开启后消费者可小程序下单选择“堂食”，然后用户到店核销"
              inactive-text="堂食"
            />
          </li>
          <li>
            <el-switch
              v-model="form.diningConfigJson.isPack"
              active-text="注：开启后消费者可小程序下单选择“打包”"
              inactive-text="打包"
            />
          </li>
          <li v-if="form.diningConfigJson.isPack">
            <el-form-item label="基础打包费：" prop="diningConfigJson.packFee">
              <el-input
                v-model="form.diningConfigJson.packFee"
                placeholder="请输入"
                show-word-limit
              />
              元
              <p>
                注：打包订单每单按照设置金额收取消费者打包费，不可负数，支持输入小数2位
              </p>
            </el-form-item>
          </li>

          <li>
            <el-switch
              v-model="form.diningConfigJson.isDelivery"
              active-text="注：开启后消费者可小程序下单选择“外卖配送”，商户自行配送"
              inactive-text="外卖配送"
            />
          </li>
          <li v-if="form.diningConfigJson.isDelivery">
            <el-form-item
              label="基础配送费："
              prop="diningConfigJson.deliveryFee"
            >
              <el-input
                v-model="form.diningConfigJson.deliveryFee"
                placeholder="请输入"
                show-word-limit
              />
              元
              <p>
                注：外卖配送订单每单按照设置金额收取消费者配送费，不可负数，支持输入小数2位
              </p>
            </el-form-item>
          </li>
        </ul>
      </el-form-item>
      <el-form-item v-else label="配送服务：">
        <ul class="fl">
          <li>
            <el-switch
              v-model="form.deliveryServiceConfigJson.isShopConsume"
              active-text="注：开启后消费者可小程序下单选择“到店消费”，然后用户到店核销"
              inactive-text="到店消费"
            />
          </li>
          <li>
            <el-switch
              v-model="form.deliveryServiceConfigJson.isSelfPack"
              active-text="注：开启后消费者可小程序下单选择“自提”"
              inactive-text="自提"
            />
          </li>
          <li v-if="form.deliveryServiceConfigJson.isSelfPack">
            <el-form-item
              label="基础打包费："
              prop="deliveryServiceConfigJson.packFee"
            >
              <el-input
                v-model="form.deliveryServiceConfigJson.packFee"
                placeholder="请输入"
                show-word-limit
              />
              元
              <p>
                注：自提订单每单按照设置金额收取消费者打包费，不可负数，支持输入小数2位
              </p>
            </el-form-item>
          </li>

          <li>
            <el-switch
              v-model="form.deliveryServiceConfigJson.isDelivery"
              active-text="注：开启后消费者可小程序下单选择“外卖配送”，商户自行配送"
              inactive-text="外卖配送"
            />
          </li>
          <li v-if="form.deliveryServiceConfigJson.isDelivery">
            <el-form-item
              label="基础配送费："
              prop="deliveryServiceConfigJson.deliveryFee"
            >
              <el-input
                v-model="form.deliveryServiceConfigJson.deliveryFee"
                placeholder="请输入"
                show-word-limit
              />
              元
              <p>
                注：外卖配送订单每单按照设置金额收取消费者配送费，不可负数，支持输入小数2位
              </p>
            </el-form-item>
          </li>
        </ul>
      </el-form-item>
      <el-form-item v-if="typeTips">
        <div class="recharge-tips app-text-color-danger">
          {{
            form.industry === "1"
              ? "请至少设置一种就餐方式"
              : "请至少设置一种配送服务"
          }}
        </div>
      </el-form-item>

      <!-- <el-form-item label="支付方式" prop="payChannels">
        <div>
          <el-checkbox-group v-model="form.payChannels">
            <el-checkbox
              v-for="(v, k, i) in payChannelsOptions"
              :key="i"
              :label="k"
              >{{ v }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </el-form-item> -->

      <!-- <el-form-item label="店铺图片：" prop="imageList">
        <div class="img-list-container">
          <draggable
            :list="form.imageList"
            :options="{ filter: '.undrag' }"
            style="display: flex; flex-wrap: wrap"
          >
            <div
              v-for="(v, i) in form.imageList"
              :key="i"
              class="img-item drag"
            >
              <img :src="v.url" alt class="imgs" />
              <div class="handle-icon">
                <i class="el-icon-zoom-in icon" @click="handlePreview(v)" />
                <i class="el-icon-delete icon" @click="handleImgRemove(v, i)" />
              </div>
            </div>

            <div class="img-item undrag">
              <el-upload
                :limit="10"
                :action="actionUrl"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :file-list="form.imageList"
                :before-upload="handleImgBefore"
                :on-success="handleImgSuccess"
                :on-exceed="handleImgExceed"
                drag
                multiple
                :show-file-list="false"
                list-type="picture-card"
                class="upload-container"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
              <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
            </div>
          </draggable>
        </div>
        <div class="upload-tips">
          <div>1.只能上传jpg/png文件，且不超过1mb</div>
          <div>2.建议尺寸1060*530像素，最多上传10张</div>
          <div>3.可长按图片进行拖拽排序</div>
        </div>
      </el-form-item> -->

      <!-- <el-form-item label="联系电话：" prop="mobilePhone">
        <el-input
          v-model="form.mobilePhone"
          placeholder="请输入"
          :disabled="form_disabled"
        />
      </el-form-item> -->

      <!-- <el-form-item label="店铺公告：" prop="shopNotice">
        <el-input
          v-model="form.shopNotice"
          placeholder="请输入"
          type="textarea"
          maxlength="200"
          show-word-limit
        />
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" size="medium" round @click="onSubmit('form')">
          {{ type === "edit" ? "提交" : "创建" }}
        </el-button>
        <el-button size="medium" round @click="routerBack()">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 图库 -->
    <card-img-map ref="cardImgMap" img-type="LOGO" />
  </div>
</template>
<script>
import {
  getBusinessClassificationList,
  getPubClassifyList,
  getPubDomainBusinessIndustryList,
  getPubIndustryList
} from '@/publicApi/BusineCenter'

const STATUS = {
  // status 0:已打烊  1:正常营业  2:部分营业
  CLOSED: 0,
  NORMAL: 1,
  PARTIAL: 2
}
const STATUS_TEXT = {
  [STATUS.CLOSED]: '已打烊',
  [STATUS.NORMAL]: '正常营业',
  [STATUS.PARTIAL]: '部分营业'
}
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import { getArea } from '@/api/shop'
import { validateAllPhone, validateStrLen } from '@/utils/validate.js'
import {
  getShopInfo,
  createShop,
  updateShop,
  updateShopStatus
} from '@/api/shop'
import {
  getDetail,
  getPubDomainShop,
  getPubShopList,
  updatePubShop
} from '@/api/BusineCenter'
import TencentMap from '@/components/TencentMap/TencentMap'
import draggable from 'vuedraggable'
import store from '@/store'
let initProvinceCode = ''
export default {
  components: {
    TencentMap,
    draggable
  },
  props: {
    type: {
      require: true,
      type: String
    },
    id: null
  },
  data() {
    /**
     * 表单校验方法相关
     */
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!validateStrLen(value, 400)) {
        callback(new Error('长度不超过200个汉字或400个字符'))
      } else {
        callback()
      }
    }
    const validateTelPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入联系电话'))
      } else if (!validateAllPhone(value)) {
        callback(
          new Error(
            '请输入手机号或固话(格式：8888888、020-8888888、(020)8888888'
          )
        )
      } else {
        callback()
      }
    }
    const validateAddress = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入店铺地址'))
      } else if (!validateStrLen(value, 200)) {
        callback(new Error('长度不超过100个汉字或200个字符'))
      } else {
        callback()
      }
    }
    const validatePackFee = (rule, value, callback) => {
      const find = value.toString().indexOf('.')
      if (value === '') {
        callback(new Error('不可为空'))
      } else if (value < 0) {
        callback(new Error('不可为负数'))
      } else if (find && value.length - (find + 1) > 2) {
        callback(new Error('仅支持输入小数2位'))
      } else {
        callback()
      }
    }
    return {
      /**
       * 表单校验字段相关
       */
      rules: {
        // Logo图
        logo: [
          {
            required: true,
            message: '请上传店铺LOGO图',
            trigger: ['change']
          }
        ],
        // 名称
        shopName: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        shopNotice: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        fullname: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        // 手机号
        mobilePhone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        address: [
          {
            required: true,
            validator: validateAddress,
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        latitude: [
          {
            required: true,
            message: '请选择店铺所在位置',
            trigger: ['blur', 'change']
          }
        ],
        customParamsOpenTime: [
          {
            required: true,
            message: '请选择营业时间',
            trigger: 'change'
          }
        ],
        // 支付方式
        payChannels: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一种支付渠道'
          }
        ],
        imageList: {
          type: 'array',
          required: true,
          message: '请上传店铺图片',
          trigger: ['change']
        },
        // 就餐规则
        'diningConfigJson.packFee': {
          required: true,
          validator: validatePackFee,
          trigger: ['blur', 'change']
        },
        'diningConfigJson.deliveryFee': {
          required: true,
          validator: validatePackFee,
          trigger: ['blur', 'change']
        },
        // 配送规则
        'deliveryServiceConfigJson.packFee': {
          required: true,
          validator: validatePackFee,
          trigger: ['blur', 'change']
        },
        'deliveryServiceConfigJson.deliveryFee': {
          required: true,
          validator: validatePackFee,
          trigger: ['blur', 'change']
        }
      },
      loading: false,
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      payChannelsOptions: {
        0: '微信支付',
        1: '会员钱包'
      },
      form: {
        icon: '',
        name: '',
        fullName: '',
        mobilePhone: '',
        servicePhone: '',
        address: '',
        landmark: '',
        latitude: '',
        longitude: '',
        provinceCode: '',
        cityCode: '',
        desc: '',
        shopNotice: '',
        areaCode: '',
        copywrite: '',
        openTimeType: 1, // 营业时间标识 1 代表营业时间 2代表非营业时间
        customParamsOpenTime: '',
        isTrade: '',
        payChannels: [],
        imageList: [],

        industry: '', // 门店类型:1.茶餐饮 2.零售 3.休闲娱乐 4.综合商业体
        // 就餐方式
        diningConfigJson: {
          isEatShop: false, // 是否堂食
          isPack: false, // 是否打包
          packFee: '', // 打包费
          isDelivery: false, // 是否配送
          deliveryFee: '' // 配送费
        },
        // 配送服务
        deliveryServiceConfigJson: {
          isShopConsume: false, // 是否到店消费
          isSelfPack: false, // 是否自提
          packFee: '', // 打包费
          isDelivery: false, // 是否配送
          deliveryFee: '' // 配送费
        },
        // 新增商圈信息
        pubDomainClassifyId: '',
        pubDomainIndustryId: '',
        images: ''
      },
      typeTips: false, // 方式提示
      customParamsOpenTimeSwitch: false,
      form_disabled: false,
      /* 地图（腾讯和高德）*/
      chooseAddr: {},
      mapSrc: '',
      tencentMapSrc: '', // 腾讯地图地址
      options: '',
      selectedOptions: ['广东省', '广州市', '荔湾区'], // 选择的地址默认
      STATUS_TEXT,
      dialogImageVisible: false,
      dialogImageUrl: '',
      // 省市区
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const that = this
          const { level, label } = node
          setTimeout(() => {
            if (level === 1) {
              // 加载市
              node.children = [] // 防止加载重复数据
              this.provinceName = label
              const data = {
                provinceName: label,
                type: 2
              }
              getArea(data).then((res) => {
                resolve(res.data)
              })
            } else if (level === 2) {
              // 加载区
              node.children = []
              const data = {
                provinceName: this.provinceName || initProvinceCode,
                code: label,
                type: 3
              }
              getArea(data).then((res) => {
                res.data.forEach((el) => {
                  el.leaf = level >= 2 // 取消最后一级箭头
                })
                resolve(res.data)
              })
            }
          }, 100)
        }
      },
      // 门店分类
      businessClassificationList: [],
      pubIndustryList: [],
      businessDetail: null
    }
  },
  watch: {
    isBusinessDistrictMainStore(val) {
      if (val) {
        // 增加校验规则
        this.rules.images = [
          {
            required: true,
            message: '请选择门店图片',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'userInfo', 'businessInfo']),
    // 1.支持商圈商户为主店、直营、独立门店配置门店分类,配置门店类型
    // 支持商户上传主店的图片，非主店、非商圈主店无图片字段，
    isBusinessDistrictMainStore({ businessDetail }) {
      return businessDetail?.pubTag === 1 && businessDetail?.shopType === 3
    },
    isMainStore({ businessDetail }) {
      // 当前登陆的是主店
      return businessDetail?.mainShopStatus
    }
  },
  mounted() {
    this.fetchData()
    this.getBusinessClassificationList()
    this.getPubIndustryList()
    this.initBusinessInfoData()
  },
  methods: {
    // 获取主店数据
    async initBusinessInfoData() {
      let detail = {}
      const { code, data } = await getDetail({
        id: this.businessInfo.syncTmpMerchantId
      })
      if (code === 0) {
        detail = {
          ...data
        }
      }
      const res = await this.$store.dispatch('GetInfo')
      if (res?.data) {
        const { data } = res
        detail = {
          ...detail,
          ...data
        }
        this.businessDetail = detail
        if (this?.isMainStore) {
          this.rules.pubDomainIndustryId = [
            {
              required: true,
              message: '请选择门店类型',
              trigger: 'change'
            }
          ]
        }
        if (this.isBusinessDistrictMainStore) {
          this.rules.pubDomainClassifyId = [
            {
              required: true,
              message: '请选择门店分类',
              trigger: 'change'
            }
          ]
        }
      }
    },

    // 获取门店分类
    async getBusinessClassificationList() {
      const params = {
        pubDomainBusinessId: this.$route.params?.id,
        pageSize: 999,
        page: 1
      }
      const { code, data } = await getPubClassifyList({
        ...params
      })
      if (code === 0) {
        this.businessClassificationList = data
      }
    },
    // 获取公域商圈行业类型
    async getPubIndustryList() {
      const params = {
        pubDomainBusinessId: this.$route.params?.id,
        pageSize: 999,
        page: 1
      }
      const { code, data } = await getPubDomainBusinessIndustryList({
        ...params
      })
      if (code === 0) {
        for (const dataKey in data) {
          const value = data[dataKey]
          const obj = {
            name: value,
            id: Number(dataKey)
          }
          this.pubIndustryList.push(obj)
        }
        // this.pubIndustryList = data
      }
    },
    // 门店背景图
    handleBusinessBgUploadSuccess(res, file) {
      if (res.code === 0) {
        this.form.images = res.data.path
        this.$refs.form.clearValidate(['images'])
      } else {
        this.$message.error(res.msg)
      }
    },
    // 上传预处理
    beforeBusinessBgUpload(file) {
      return this.beforeUploadImg(file, this, 300, 300, 0.5)
    },
    onClickStopStore() {
      const text = this.form.disabled ? '启用' : '关停'
      this.$confirm(
        `您确定${text}门店佛山市禅城区陈阳大厦”的所有服务?包括商城、餐饮、服务、场所等。`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async() => {
        const { code } = await updateShopStatus({
          disabled: !this.form.disabled,
          shopId: this.id
        })
        if (code === 0) {
          this.$message({
            type: 'success',
            message: '成功!'
          })
          this.fetchData()
        }
      })
    },
    onClickCloseStore() {
      const text = this.form.status === 0 ? '关闭打烊' : '打烊'
      this.$confirm(
        `您确定${text}门店“佛山市禅城区陈阳大厦”的所有服务?包括商城、餐饮、服务、场所等。`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async() => {
        const { code } = await updateShopStatus({
          shopId: this.id,
          status: this.form.status === 0 ? 1 : 0
        })
        if (code === 0) {
          this.$message({
            type: 'success',
            message: '成功!'
          })
          this.fetchData()
        }
      })
    },
    // 上传图片
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1)
    },

    handleImgSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.form.imageList = fileList
        this.$refs.form.clearValidate(['imageList'])
      } else {
        this.$message.error(res.msg)
      }
    },

    handleImgRemove(v, i) {
      this.form.imageList.splice(i, 1)
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    handleImgExceed() {
      this.$message.error('最多上传10张')
    },
    /**
     * 获取数据
     */
    // 获取店铺信息
    fetchData() {
      // 设置修改权限
      const syncTmpMerchantId = this.userInfo.business.syncTmpMerchantId
      if (syncTmpMerchantId) {
        this.form_disabled = true
      } else {
        this.form_disabled = false
      }

      if (this.type === 'edit') {
        getPubDomainShop(this.id).then((res) => {
          // const { openHour, openMin, closeHour, closeMin, payChannels, provinceCode, cityCode, areaCode } = res.data;
          const {
            openHour,
            openMin,
            closeHour,
            closeMin,
            provinceCode,
            cityCode,
            areaCode
          } = res.data
          res.data.customParamsOpenTime = [
            `${openHour}:${openMin}`,
            `${closeHour}:${closeMin}`
          ]
          // res.data.payChannels = payChannels.split(',');
          if (!res.data.imageList) res.data.imageList = []
          res.data.imageList = res.data.imageList.map((v) => {
            return {
              response: {
                code: 0,
                data: {
                  path: v
                }
              },
              url: this.fileBaseUrl + v
            }
          })
          res.data.diningConfigJson.deliveryFee =
            res.data.diningConfigJson.deliveryFee / 100
          res.data.diningConfigJson.packFee =
            res.data.diningConfigJson.packFee / 100
          res.data.deliveryServiceConfigJson.deliveryFee =
            res.data.deliveryServiceConfigJson.deliveryFee / 100
          res.data.deliveryServiceConfigJson.packFee =
            res.data.deliveryServiceConfigJson.packFee / 100
          res.data.pubDomainClassifyId = res.data.pubDomainClassifyId
            ? Number(res.data.pubDomainClassifyId)
            : ''
          res.data.pubDomainIndustryId = res.data.pubDomainIndustryId
            ? Number(res.data.pubDomainIndustryId)
            : ''
          this.customParamsOpenTimeSwitch = res.data.isTrade === 0
          this.form = res.data
          console.log('门店配置----', this.form)

          // 腾讯地图和高德地图设置
          this.tencentMapSrc = `https://apis.map.qq.com/tools/locpicker?coord=${
            res.data.longitude ? res.data.longitude : 113.258339809
          },${
            res.data.latitude ? res.data.latitude : 23.149134849
          }&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18`
          // 地址选择默认值处理
          if (this.form.provinceCode) {
            this.getProvinceFunc(provinceCode, cityCode, areaCode)
          }
        })
      } else {
        // add
        this.handleChooseAddressChange(this.selectedOptions)
        this.tencentMapSrc = `https://apis.map.qq.com/tools/locpicker?coord=113.258339809,23.149134849&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18`
      }
    },

    /**
     * 按钮组
     */
    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.logo = res.data.path
        this.$refs.form.clearValidate(['logo'])
      } else {
        this.$message.error(res.msg)
      }
    },
    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 300, 300, 0.5)
    },
    // 提交
    onSubmit(formName) {
      // 配送/就餐方式
      // console.log('isEatShop',this.form.diningConfigJson.isEatShop)
      // console.log('isPack',this.form.diningConfigJson.isPack)
      // console.log('isDelivery1',this.form.diningConfigJson.isDelivery)
      // console.log('isShopConsume',this.form.deliveryServiceConfigJson.isShopConsume)
      // console.log('isSelfPack',this.form.deliveryServiceConfigJson.isSelfPack)
      // console.log('isDelivery2',this.form.deliveryServiceConfigJson.isDelivery)
      if (
        !this.form.diningConfigJson.isEatShop &&
        !this.form.diningConfigJson.isPack &&
        !this.form.diningConfigJson.isDelivery &&
        !this.form.deliveryServiceConfigJson.isShopConsume &&
        !this.form.deliveryServiceConfigJson.isSelfPack &&
        !this.form.deliveryServiceConfigJson.isDelivery
      ) {
        this.typeTips = true
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const thisForm = JSON.stringify(this.form)
          const params = JSON.parse(thisForm)
          console.log('params=====', params)
          // params.payChannels = params.payChannels.join(',');
          // 格式化时间
          const openTime = params.customParamsOpenTime[0].split(':')
          const closeTime = params.customParamsOpenTime[1].split(':')
          const packFee = params.diningConfigJson.packFee * 100
          const deliveryFee = params.diningConfigJson.deliveryFee * 100
          const desPackFee = params.deliveryServiceConfigJson.packFee * 100
          const desDeliveryFee =
            params.deliveryServiceConfigJson.deliveryFee * 100
          params.openHour = openTime[0]
          params.openMin = openTime[1]
          params.closeHour = closeTime[0]
          params.closeMin = closeTime[1]
          params.diningConfigJson.packFee = packFee
          params.diningConfigJson.deliveryFee = deliveryFee
          params.deliveryServiceConfigJson.packFee = desPackFee
          params.deliveryServiceConfigJson.deliveryFee = desDeliveryFee
          params.isTrade = this.customParamsOpenTimeSwitch ? 0 : 1
          params.imageList = params.imageList.map((v) => {
            if (
              v.response &&
              v.response.code === 0 &&
              v.response.data &&
              v.response.data.path
            ) {
              return v.response.data.path
            }
          })
          delete params.customParamsOpenTime
          this.loading = true
          if (this.type === 'add') {
            createShop(params)
              .then((res) => {
                if (res.code === 0) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000,
                    offset: 40
                  })
                  this.loading = false
                  this.$store.dispatch('GetManageShop')
                  this.$router.push({
                    name: 'storeManage'
                  })
                } else {
                  this.loading = false
                  this.$message.error(res.msg)
                }
              })
              .finally(() => {
                this.loading = false
              })
          } else if (this.type === 'edit') {
            updatePubShop(params)
              .then((res) => {
                if (res.code === 0) {
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000,
                    offset: 40
                  })
                  this.loading = false
                  this.$store.dispatch('GetManageShop')
                  this.$router.push({
                    name: 'storeManage'
                  })
                } else {
                  this.loading = false
                  this.$message.error(res.msg)
                }
              })
              .finally(() => {
                this.loading = false
              })
          }
        } else {
          return false
        }
      })
    },
    // 取消
    routerBack() {
      this.$router.push({
        name: 'storeManage'
      })
    },
    // 打开图库
    openCardImgMap() {
      this.$refs.cardImgMap.open().then((res) => {
        this.form.logo = res
      })
    },
    // 地图选择
    getPackingLocation(addrLocation) {
      console.log('addrLocation---', addrLocation)
      this.form.latitude = addrLocation.latlng.lat
      this.form.longitude = addrLocation.latlng.lng
      this.$refs.form.clearValidate(['latitude'])
    },

    // 初始默认赋值 - 省市区
    getProvinceFunc(lable, cityCode, areaCode) {
      // 请求省
      const data = {
        type: 1
      }
      let provinceList = ''
      getArea(data).then((res) => {
        provinceList = res.data
        // 请求市
        const data = {
          provinceName: lable,
          type: 2
        }
        let provinceIndex = ''
        provinceList.forEach((el, index) => {
          if (el.label === lable) {
            provinceIndex = index
          }
        })
        getArea(data).then((res) => {
          provinceList[provinceIndex].children = res.data
          const data = {
            provinceName: lable,
            code: cityCode,
            type: 3
          }
          let cityIndex = ''
          provinceList[provinceIndex].children.forEach((el, index) => {
            if (el.label === cityCode) {
              cityIndex = index
            }
          })
          // 请求区
          getArea(data).then((res) => {
            res.data.forEach((el) => {
              el.leaf = true // 回显必填
            })
            provinceList[provinceIndex].children[cityIndex].children = res.data // 某个市children
            this.options = provinceList
            // 设置值
            initProvinceCode = lable // 设置默认的省
            this.selectedOptions = [lable, cityCode, areaCode]
          })
        })
      })
    },
    handleChooseAddressChange(value) {
      console.log('value', value)
      this.form.provinceCode = value[0]
      this.form.cityCode = value[1]
      this.form.areaCode = value[2]
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.business-store-edit {
  .instructions {
    border: 1px solid #dcdfe6;
    padding: 16px;
    box-sizing: border-box;
    margin: 15px 0 50px;

    h3 {
      margin-bottom: 16px;
      font-size: 1.17em;
      font-weight: 500;
    }

    p {
      font-weight: 200;
    }
  }

  .img-item {
    width: 15%;
    margin-right: 20px;
    margin-top: 20px;
  }

  .default_msg {
    margin-left: 140px;
    color: #9e9e9e;
    font-size: 12px;
  }

  .el-input,
  .el-textarea {
    width: 70%;
    max-width: 600px;
  }

  .app-uploader-img-plus {
    width: 180px;
    height: 180px;

    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 180px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }

    .avatar {
      width: 180px;
      height: 180px;
      display: block;
    }
  }

  .upload_tips {
    margin: 20px 0 0 20px;

    li {
      margin-top: 10px;
      font-size: 14px;
      line-height: 16px;
      color: $dark-font-color;
    }
  }
}

.img-list-container {
  width: 100vw;

  .drag {
    position: relative;
  }

  .imgs {
    min-width: 200px;
    min-height: 200px;
    object-fit: cover;
  }

  .handle-icon {
    position: absolute;
    top: -10px;
    right: 2px;
  }
}

.upload-tips {
  div {
    color: $dark-font-color;
  }
}
</style>
